import * as React from "react";

interface Options {
  loop?: boolean;
  roll?: boolean;
}

export const useScrollToBottom = <T extends Element>({
  loop = true,
  roll = false,
}: Options = {}): [React.RefCallback<T>, boolean] => {
  const [isBottom, setIsBottom] = React.useState(false);
  const [node, setRef] = React.useState<any>(null);
  const timer = React.useRef(null);

  React.useEffect(() => {
    let observer: IntersectionObserver;

    if (node && node.parentElement) {
      observer = new IntersectionObserver(
        ([entry]) => {
          setIsBottom(entry.isIntersecting);
          if (!loop && entry.isIntersecting) {
            observer.disconnect();
          }
        },
        {
          root: node.parentElement,
        },
      );
      observer.observe(node);
    } else {
      setIsBottom(false);
    }

    return () => {
      if (observer) {
        observer.disconnect();
      }
    };
  }, [node]);

  React.useEffect(() => {
    // timer
    if (roll) {
      if (node && node.parentElement) {
        node.parentElement.addEventListener("touchstart", () => clearTimeout());
        if (!timer.current) {
          timer.current = setInterval(() => {
            node.parentElement.scrollTop += 1;
          }, 50);
        }
        if (isBottom) clearTimeout();
      }
    }
    return () =>
      node &&
      node.parentElement &&
      node.parentElement.removeEventListener("click", () => clearTimeout());
  }, [node, isBottom]);

  const clearTimeout = () => {
    if (timer.current) {
      clearInterval(timer.current);
      timer.current = null;
    }
  };

  return [setRef, isBottom];
};
export default useScrollToBottom;
